package cn.b.sky.mes.mm.service.impl;

import java.util.List;

import cn.b.sky.mes.mm.dao.SupplierDao;
import cn.b.sky.mes.mm.model.Supplier;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.b.sky.mes.mm.model.condition.SupplierCondition;
import cn.b.sky.mes.mm.service.SupplierService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.utils.DatabaseUtils;

@Service("supplierService")
public class SupplierServiceImpl implements SupplierService {

  private static final Logger LOG = LoggerFactory.getLogger(SupplierServiceImpl.class);

  @Autowired
  public SupplierDao supplierDao;

  @Override
  public List<Supplier> getSuppliersByCondition(SupplierCondition condition) {
    if (condition == null) {
      return null;
    }
    if (StringUtils.isBlank(condition.getOrderField())) {
      condition.setOrderField("modifyDatetime");//修改时间排序
    }
    return supplierDao.selectSupplierByCondition(condition);
  }

  @Override
  public int getSupplierCountByCondition(SupplierCondition condition) {
    if (condition == null) {
      return 0;
    }
    return supplierDao.selectSupplierCountByCondition(condition);
  }

  @Override
  public Supplier getSupplierBySupplierCode(String siteCode, String supplierCode) {
    if (StringUtils.isBlank(supplierCode) || StringUtils.isBlank(siteCode)) {
      return null;
    }
    return supplierDao.selectSupplierByPk(siteCode, supplierCode);
  }

  @Override
  public void saveSupplier(Supplier supplier) {
    if (supplier != null && !StringUtils.isBlank(supplier.getSupplierCode())) {
      supplierDao.insertSupplier(supplier);
    }
  }

  @Override
  public void modifySupplier(Supplier supplier) {
    if (supplier != null && !StringUtils.isBlank(supplier.getSupplierCode())) {
      supplierDao.updateSupplier(supplier);
    }
  }

  @Override
  public String deleteSupplierBySiteCodeAndSupplierCode(String siteCode, String supplierCode) {
    String message = "";
    if (StringUtils.isBlank(siteCode) || StringUtils.isBlank(supplierCode)) {
      return null;
    }
    try {
      supplierDao.deleteSupplierByPk(siteCode, supplierCode);
    } catch (Exception e) {
      LOG.error("{}", e);
      String errorMsg = e.getMessage();
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        // 外键删除已存在提示
        message = SystemConstant.DATABASE_OPERATION_FK;
      } else {
        message = SystemConstant.DWZ_CODE_ERROR_MESSAGE;
      }
    }
    return message;
  }

  @Override
  public List<Supplier> getSuppliersSuggests(SupplierCondition condition) {
    return supplierDao.getSuppliersSuggests(condition);
  }

}
